package com.lin.sunnyweather.logic

import androidx.lifecycle.liveData
import com.lin.sunnyweather.logic.network.SunnyWeatherNetwork
import kotlinx.coroutines.Dispatchers

/** 仓库层 */
object Repository {

    //请求成功代码
    private const val ResponseSuccessCode = "200"

    fun searchPlace(location: String) = liveData(Dispatchers.IO) {
        val result = try {
            val response = SunnyWeatherNetwork.searchPlaces(location)
            if (response.code == ResponseSuccessCode) {
                val result = response.location
                Result.success(result)
            } else {
                Result.failure(RuntimeException("response code is ${response.code}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
        emit(result)
    }

    fun nowWeather(location: String) = liveData(Dispatchers.IO) {
        val result = try {
            val response = SunnyWeatherNetwork.nowWeather(location)
            if (response.code == ResponseSuccessCode) {
                val result = response.now
                Result.success(result)
            } else {
                Result.failure(RuntimeException("response code is ${response.code}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
        emit(result)
    }

    fun threeDayWeather(location: String) = liveData(Dispatchers.IO) {
        val result = try {
            val response = SunnyWeatherNetwork.threeDayWeather(location)
            if (response.code == ResponseSuccessCode) {
                val result = response.daily
                Result.success(result)
            } else {
                Result.failure(RuntimeException("response code is ${response.code}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
        emit(result)
    }

    fun lifeIndex(location: String) = liveData(Dispatchers.IO) {
        val result = try {
            val response = SunnyWeatherNetwork.lifeIndex(location)
            if (response.code == ResponseSuccessCode) {
                val result = response.daily
                Result.success(result)
            } else {
                Result.failure(RuntimeException("response code is ${response.code}"))
            }
        } catch (e: Exception) {
            Result.failure(e)
        }
        emit(result)
    }
}